package com.zyl.timer;

import java.io.IOException;
import java.util.Date;

import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.Service;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.IBinder;
import android.view.WindowManager;

import com.zyl.points.bean.Question;
import com.zyl.points.service.QuestionService;
import com.zyl.points.util.FileUtil;
 

public class TimerService extends Service {

	@Override
	public IBinder onBind(Intent intent) {

		return null;

	}

	@Override
	public void onCreate() {
		super.onCreate();

	}

	@Override
	public void onDestroy() {

	}
	private QuestionService questionService;
	@Override
	public void onStart(Intent intent, int startid) {
		 questionService =new QuestionService(TimerService.this); 
		 log();
	}

	 
	public void log() { 
		 String message="";
		 final Question q =questionService.randomQuestion();
		 
		Date d = new Date(System.currentTimeMillis());
		message=q.getTitle()+"\n"+q.getAnswer();
		
		if(d.getHours()<9||d.getHours()>21){
			return;
		}
		if(d.getMinutes()!=1){
			return;
		}
	
	  	vibrator();
		
 
		 final String str=  d.getHours()+" " ;
 
		  
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setMessage(message).setPositiveButton("√", new DialogInterface.OnClickListener() { 
		             @Override 
		             public void onClick(DialogInterface dialog, int which) { 
		            	 try {
			     			
							FileUtil.write(str+"  "+q.getTitle()+"  √" );
							questionService.reduceAppearTimes(q.getId());
							
			     			} catch (IOException e) {
			     				 
			     			} 
		             } 
		         }). 
		         setNegativeButton("x", new DialogInterface.OnClickListener() { 
		             public void onClick(DialogInterface dialog, int which) { 
		            	 try {
				     			
								FileUtil.write(str+"  "+q.getTitle()+"  x" );
								questionService.addAppearTimes(q.getId());
				     			} catch (IOException e) {
				     				 
				     			} 
		             } 
		         });
				AlertDialog ad = builder.create(); //
				ad.getWindow().setType(
						WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
				// 系统中关机对话框就是这个属性
				ad.getWindow()
						.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
				ad.setCanceledOnTouchOutside(false);
				// 点击外面区域不会让dialog消失
				ad.show();

	
	}
	public void vibrator( ) {
		Intent i = new Intent(this, TimerVibrator.class);
		PendingIntent pi = PendingIntent.getBroadcast(this.getApplicationContext(), 0, i, 0);
		AlarmManager am = (AlarmManager) this.getSystemService(ALARM_SERVICE);
		am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 1000,
				pi);
		
		
	}
	
}
